<template>
  <el-dialog :visible.sync="dialogFormVisible"
             title="移动文件"
             :before-close="onClose"
             destroy-on-close
             :fileIds="fileIds"
             :parentId="parentId"
  >
    <el-radio-group v-model="pid">
      <el-tree :props="defaultProps"
               @node-click="handleNodeClick"
               :load="loadNode"
               node-key="id"
               :default-expanded-keys="[0]"
               lazy
               :expand-on-click-node=false
               accordion
               :current-node-key="pid"
      >
        <span class="tree-node"
              :class="[isIdCanSelect(data.id)?'enable-node':'unable-node']"
              slot-scope="{ node, data }"
        >
          <el-radio :label="data.id" :disabled="!isIdCanSelect(data.id)">{{ node.label }}</el-radio>
        </span>
      </el-tree>
    </el-radio-group>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="submitMove">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import moveFiles from "@/views/home/api/moveFiles";
import directoryTree from "@/views/home/api/directoryTree";

export default {
  name: "MoveFileModal",
  props: {
    dialogFormVisible: Boolean,
    fileIds: Array,
    parentId: Number
  },
  data() {
    return {
      pid: 0,
      root: {
        id: 0,
        title: 'root'
      },
      defaultProps: {
        label: 'title',
        children: 'children',
        isLeaf: 'leaf',
        id: 'id'
      },
    }
  },
  methods: {
    onClose() {
      this.$emit('onClose');
    },
    async submitMove() {
      if (this.pid === undefined) {
        this.$message.warning("请选择目标目录");
        return;
      }
      let response = await moveFiles(this.fileIds, this.pid);
      if (response.success) {
        this.$emit("onSuccess");
        this.onClose();
      }
    },
    handleNodeClick(directory) {
      if (this.isIdCanSelect(directory.id)) {
        this.pid = directory.id;
      }
    },
    async loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([this.root]);
      }
      let response = await directoryTree(node.data.id);
      if (!response.success) {
        this.$message(response.message);
        this.onClose();
        return;
      }
      let children = response.data.children;
      if (children.length === 0) {
        return resolve([]);
      }
      return resolve(children)
    },
    isIdCanSelect(id) {
      if (id === this.parentId) {
        return false;
      }
      for (let fileId of this.fileIds) {
        if (id === fileId) {
          return false;
        }
      }
      return true;
    }
  }
}
</script>

<style scoped lang="less">

.tree-node {
  user-select: none;
}

.enable-node {
  font-weight: bold;
}

.unable-node {
  color: gray;
  cursor:no-drop;
}
</style>